package com.lyn.chapter4.demo1;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.atomic.AtomicLong;

import com.lyn.kit.Tools;

public class Storage implements Closeable, AutoCloseable{
	private final RandomAccessFile storeFile;
	private final FileChannel storeChannel;
	protected final AtomicLong totalWrites = new AtomicLong(0);
	
	public Storage(long fileSize, String fileShortName) throws IOException {
		String fullFileName = System.getProperty("java.io.tmpdir") + "/"
				+ fileShortName;
		String localFileName;
		localFileName = createStoreFile(fileSize, fullFileName);
		storeFile = new RandomAccessFile(localFileName, "rw");
		storeChannel = storeFile.getChannel();
	}
	
	public int store(long offset, ByteBuffer byteBuf) throws IOException{
		int length;
		storeChannel.write(byteBuf, offset);
		length = byteBuf.limit();
		totalWrites.addAndGet(length);
		return length;
	}
	
	/**
	 * 获得已写入的数据量大小
	 * @return
	 */
	public long getTotalWrites() {
		return totalWrites.get();
	}
	
	/**
	 * 在本地创建文件
	 * @param fileSize
	 * @param fullFileName
	 * @return
	 * @throws IOException
	 */
	private String createStoreFile(final long fileSize, String fullFileName) throws IOException{
		File file = new File(fullFileName);
		System.out.println("create local file:"+fullFileName);
		RandomAccessFile raf;
		raf = new RandomAccessFile(file, "rw");
		try {
			raf.setLength(fileSize);
		} finally {
			Tools.silentClose(raf);
		}
		return fullFileName;
	}
	
	/**
	 * 关闭nio的相关资源
	 */
	@Override
	public void close() throws IOException {
		if(storeChannel.isOpen()) {
			Tools.silentClose(storeChannel, storeFile);
		}
	}


}
